<template>
  <div class="supply-planning-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>供应计划管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon><Plus /></el-icon>
              新建计划
            </el-button>
            <el-button type="success" @click="autoGenerate">
              <el-icon><MagicStick /></el-icon>
              AI智能生成
            </el-button>
            <el-button type="info" @click="exportPlans">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :xs="24" :sm="12" :md="6" v-for="stat in statsCards" :key="stat.id">
          <div class="stat-card" :class="stat.type">
            <div class="stat-icon">
              <el-icon size="24"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-form :model="filterForm" inline>
          <el-form-item label="计划状态">
            <el-select v-model="filterForm.status" placeholder="全部" clearable>
              <el-option label="草稿" value="draft" />
              <el-option label="待审核" value="pending" />
              <el-option label="已审核" value="approved" />
              <el-option label="执行中" value="executing" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 计划列表 -->
      <el-table :data="planList" border stripe v-loading="loading">
        <el-table-column prop="planNo" label="计划编号" width="150" />
        <el-table-column prop="planName" label="计划名称" width="200" />
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="productCount" label="商品数量" width="100" align="center" />
        <el-table-column prop="totalAmount" label="计划金额" width="150" align="right">
          <template #default="{ row }">
            ¥{{ formatNumber(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="执行进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :stroke-width="8" />
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="viewDetail(row)">
              详情
            </el-button>
            <el-button type="success" size="small" link @click="editPlan(row)" v-if="row.status === 'draft'">
              编辑
            </el-button>
            <el-button type="warning" size="small" link @click="executePlan(row)" v-if="row.status === 'approved'">
              执行
            </el-button>
            <el-button type="danger" size="small" link @click="deletePlan(row)" v-if="row.status === 'draft'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form :model="planForm" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="计划周期" prop="dateRange">
          <el-date-picker
            v-model="planForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="计划说明">
          <el-input
            v-model="planForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入计划说明"
          />
        </el-form-item>
        <el-form-item label="商品需求">
          <el-button type="primary" size="small" @click="addProduct" style="margin-bottom: 10px;">
            <el-icon><Plus /></el-icon>
            添加商品
          </el-button>
          <el-table :data="planForm.products" border max-height="300">
            <el-table-column prop="productName" label="商品名称" width="200" />
            <el-table-column prop="currentStock" label="当前库存" width="100" align="center" />
            <el-table-column prop="safetyStock" label="安全库存" width="100" align="center" />
            <el-table-column prop="expectedDemand" label="预计需求" width="100" align="center" />
            <el-table-column label="计划采购" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.planQuantity"
                  :min="0"
                  size="small"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.unitPrice"
                  :min="0"
                  :precision="2"
                  size="small"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column label="金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatNumber((row.planQuantity || 0) * (row.unitPrice || 0)) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button type="danger" size="small" link @click="removeProduct($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="total-amount">
            总金额: ¥{{ formatNumber(totalAmount) }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const statsCards = ref([
  { id: 1, label: '总计划数', value: '128', icon: 'Document', type: 'primary' },
  { id: 2, label: '执行中', value: '45', icon: 'Timer', type: 'success' },
  { id: 3, label: '待审核', value: '12', icon: 'Warning', type: 'warning' },
  { id: 4, label: '本月金额', value: '¥2.5M', icon: 'Money', type: 'info' }
])

// 筛选表单
const filterForm = reactive({
  status: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const planList = ref([
  {
    id: 1,
    planNo: 'SP202401001',
    planName: '2024年Q1采购计划',
    startDate: '2024-01-01',
    endDate: '2024-03-31',
    productCount: 25,
    totalAmount: 1580000,
    status: 'executing',
    progress: 68,
    creator: '张三'
  },
  {
    id: 2,
    planNo: 'SP202401002',
    planName: '春节备货计划',
    startDate: '2024-01-15',
    endDate: '2024-02-10',
    productCount: 35,
    totalAmount: 2300000,
    status: 'approved',
    progress: 0,
    creator: '李四'
  },
  {
    id: 3,
    planNo: 'SP202401003',
    planName: '新品上市采购计划',
    startDate: '2024-02-01',
    endDate: '2024-02-28',
    productCount: 15,
    totalAmount: 950000,
    status: 'pending',
    progress: 0,
    creator: '王五'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(3)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新建供应计划')
const submitLoading = ref(false)

// 表单
const formRef = ref(null)
const planForm = reactive({
  planName: '',
  dateRange: [],
  description: '',
  products: []
})

const formRules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择计划周期', trigger: 'change' }
  ]
}

// 计算总金额
const totalAmount = computed(() => {
  return planForm.products.reduce((sum, item) => {
    return sum + (item.planQuantity || 0) * (item.unitPrice || 0)
  }, 0)
})

// 方法
const formatNumber = (value) => {
  return value.toLocaleString()
}

const getStatusType = (status) => {
  const map = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    executing: 'primary',
    completed: 'success'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    draft: '草稿',
    pending: '待审核',
    approved: '已审核',
    executing: '执行中',
    completed: '已完成'
  }
  return map[status] || status
}

const handleSearch = () => {
  ElMessage.success('查询成功')
}

const handleReset = () => {
  Object.assign(filterForm, {
    status: '',
    dateRange: []
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const showCreateDialog = () => {
  dialogTitle.value = '新建供应计划'
  Object.assign(planForm, {
    planName: '',
    dateRange: [],
    description: '',
    products: []
  })
  dialogVisible.value = true
}

const autoGenerate = () => {
  ElMessage.success('AI智能生成计划功能开发中')
}

const exportPlans = () => {
  ElMessage.success('导出计划成功')
}

const viewDetail = (row) => {
  ElMessage.info(`查看计划详情: ${row.planNo}`)
}

const editPlan = (row) => {
  dialogTitle.value = '编辑供应计划'
  Object.assign(planForm, {
    planName: row.planName,
    dateRange: [row.startDate, row.endDate],
    description: '',
    products: []
  })
  dialogVisible.value = true
}

const executePlan = (row) => {
  ElMessageBox.confirm('确定要执行此计划吗？', '确认执行', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('计划已开始执行')
  }).catch(() => {})
}

const deletePlan = (row) => {
  ElMessageBox.confirm('确定要删除此计划吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const addProduct = () => {
  planForm.products.push({
    productName: '商品名称',
    currentStock: 0,
    safetyStock: 0,
    expectedDemand: 0,
    planQuantity: 0,
    unitPrice: 0
  })
}

const removeProduct = (index) => {
  planForm.products.splice(index, 1)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      ElMessage.success('保存成功')
      dialogVisible.value = false
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.supply-planning-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card.primary { border-left: 4px solid #409eff; }
.stat-card.success { border-left: 4px solid #67c23a; }
.stat-card.warning { border-left: 4px solid #e6a23c; }
.stat-card.info { border-left: 4px solid #909399; }

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-card.primary .stat-icon { background: #409eff; }
.stat-card.success .stat-icon { background: #67c23a; }
.stat-card.warning .stat-icon { background: #e6a23c; }
.stat-card.info .stat-icon { background: #909399; }

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.total-amount {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}
</style>

